#include "ngx_memorypool.h"
#include <cstdio>
#include <cstring>
#include <cstdlib>

struct Data
{
    char *ptr;
    FILE *pfile;
};

void func1(char *p)
{
    printf("free ptr mem!\n");
    free(p);
}
void func2(FILE *pf)
{
    printf("close file!\n");
    fclose(pf);
}

int main()
{
	// 512 - sizeof(ngx_pool_t) - 4095   =>   max
    NgxMemoryPool pool(512);

    void* p1 = pool.ngx_palloc(128); // 从小块内存池分配的
    if(p1 == nullptr)
    {
        printf("ngx_palloc 128 bytes fail...\n");
        return -1;
    }

    Data* p2 = (Data*)pool.ngx_palloc(512); // 从大块内存池分配的
    if(p2 == nullptr)
    {
        printf("ngx_palloc 512 bytes fail...\n");
        return - 1;
    }

    p2->ptr = (char*)malloc(12);
    strcpy(p2->ptr, "hello world");
    p2->pfile = fopen("data.txt", "w");
    
    if (!pool.ngx_pool_cleanup_add(std::bind(func1, p2->ptr)))
    {
        printf("ngx_pool_cleanup_add func1 fail...\n");
        return -1;
    }

    if (!pool.ngx_pool_cleanup_add(std::bind(func2, p2->pfile)))
    {
        printf("ngx_pool_cleanup_add func2 fail...\n");
        return -1;
    }

    pool.ngx_reset_pool();

    return 0;
}